﻿package artibella 
{
	import flash.display.Stage;
	import flash.display.StageAlign;
	import flash.display.StageScaleMode;
	import flash.errors.IllegalOperationError;
	import flash.events.Event;

	/**
	 * ...
	 * @author pbordachar
	 */

	public class StageManager {
		
		private static var _instance:StageManager;
		
		private static var _stage:Stage;
		private static var _stageW:int;
		private static var _stageH:int;
		
		private var _tabObserver:Vector.<IStageObserver>
		

		public function StageManager( c:PrivateClass = null ){
			
			if( !c ) {
				throw new IllegalOperationError( 'Error : singleton pattern' );
			} else {

				_tabObserver = new Vector.<IStageObserver>();
			}
		}
		
		public static function get instance():StageManager
		{
			return _instance || ( _instance = new StageManager( new PrivateClass() ) );
		}
		
		///////  D E M A R R A G E

		public function setStage( s:Stage ):Boolean
		{
			if( !_stage ) {
				
				_stage = s;
				_stage.scaleMode = StageScaleMode.NO_SCALE;
				_stage.align = StageAlign.TOP_LEFT;				
				_stage.stageFocusRect = false;
			
				_getStageDimensions();
				
				return true;
				
			} else {
				
				return false;
			} 
		}
		
		public function getStage():Stage
		{
			return _stage;
		}
		
		///////  R E S I Z E

		public function addResizeListener():void
		{
			_stage.addEventListener( Event.RESIZE, _onStageResize );
			_stage.dispatchEvent( new Event( Event.RESIZE ) );
		}
		
		private function _getStageDimensions():void
		{
			_stageW = _stage.stageWidth;
			_stageH = _stage.stageHeight;
		}
		
		private function _onStageResize( e:Event = null ):void
		{
			_getStageDimensions();
			
			for( var i:int = 0, nb:int = _tabObserver.length; i < nb; i++ ) {
				_tabObserver[ i ].stageUpdate( _stageW, _stageH );
			}
		}
		
		///////  O B S E R V E R S
		
		public function addObserver( d:IStageObserver = null ):Boolean
		{
			if( !d ) {
				return false;
			} else {
				var found:Boolean = false;
				for( var i:int = 0, nb:int = _tabObserver.length; i < nb; i++ ){ 
					if( _tabObserver[ i ] == d ) found = true;
				}
				if( !found ) _tabObserver.push( d );
				return true;
			}
		}
		
		///////  U T I L S
		
		public static function get largeur():int
		{
			return _stageW;
		}
		
		public static function get hauteur():int
		{
			return _stageH;
		}
		
		public static function ajouteEvenement( eName:String, f:Function ):void
		{
			_stage.addEventListener( eName, f );
		}
		
		public static function supprimeEvenement( eName:String, f:Function ):void
		{
			if( _stage.hasEventListener( eName ) ){
				_stage.removeEventListener( eName, f );
			}
		}
	}
}

/// - - -

class PrivateClass { }
